from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, get_object_or_404
from django.template.defaultfilters import title
from django.views.decorators.http import require_POST
from django.views.generic import ListView
from django.core.paginator import Paginator

import user
from .models import Music, Classify, Love


# Create your views here.
def index(request):
    musics = Music.objects.all().only('id','Title',"author")
    classify = Classify.objects.all().only('id','title')

    return render(request, 'main/index.html',{"songs":musics,"classify":classify})


def song_detail(request):
    pk = request.GET.get('id')          # 取 URL 参数 ?id=123
    song = Music.objects.filter(pk=pk).first()
    is_love = Love.objects.filter(music_id=song.id, user_id=request.user.id).exists()

    print(999999999999999999999999999)
    print(is_love,type(is_love))
    print(999999999999999999999999999)
    if song and song.cover:
        print('111111111111')
        print(f'song.id = {song.id}, user.id = {request.user.id}')


        next_id = song.id + 1
        has_next = Music.objects.filter(id=next_id).exists()
        next_id = next_id if has_next else 1  # ① 真存在才用，否则回第一首

        up = song.id - 1
        has_up = Music.objects.filter(id=up).exists()
        up = up if has_up else Music.objects.latest('id').id  # ② 不存在就跳最后一首

        return JsonResponse({'cover': song.cover.url,'audio': song.audio.url,'id': song.id ,'userid':request.user.id,'is_love':is_love,'next_id':next_id,'up':up})

    else:
        print('查无此歌')
        return JsonResponse({'cover': '', 'audio': ''})


def classify(request):
    classify_id = request.GET.get('id')
    if classify_id:
        musics = Music.objects.filter(classifys__id=classify_id).only('id', 'Title', 'author')
    else:
        musics = Music.objects.all().only('id', 'Title', 'author')

    # 构造 JSON 响应
    music_list = [
        {
            'id': m.id,
            'Title': m.Title,
            'author': m.author,
        }
        for m in musics
    ]
    return JsonResponse({'musics': music_list})


# ✅ 正确缩进
class LoveListView(ListView):
    model = Music                # 模型
    template_name = 'main/love.html'
    context_object_name = 'love'
    paginate_by = 10



    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        paginator = context['paginator']
        current_page = context['page_obj']
        # 只拿需要的字段
        context['classify'] = Classify.objects.only('id', 'title')
        context["total_pages"] = paginator.num_pages
        return context

    def get_queryset(self):
        """
        返回：当前登录用户喜欢的所有歌曲（QuerySet）
        会被自动塞进上下文变量 love
        """
        # ⑤ 拿到当前登录用户（LoginRequiredMixin 已保证这里一定有值）
        current_user = self.request.user
        print("oooooooooooooooooooooooooo")
        print(current_user)
        print("oooooooooooooooooooooooooo")


        loved_ids = (Love.objects.filter(user = current_user )  # 只留当前用户的记录
                     .select_related('music').order_by('-liked_at'))
        print("o1111ooooooooooooooooooooooooo")
        print(f"Found {loved_ids.count()} loved songs")
        print("oo111oooooooooooooooooooooooo")

        # ⑦ 用 id 列表去 Music 表把真正的歌曲对象取出来
        loved_songs = [l.music for l in loved_ids]

        print("o111122ooooooooooooooooooooooooo")
        print(f"Retrieved {len(loved_songs)} songs")
        print("oo11122oooooooooooooooooooooooo")

        # ⑧ 把结果返回，ListView 会自动把它当作“列表数据”
        return loved_songs


def love(request):

    if request.method == 'POST':
        music_id = int(request.POST.get('id'))
        is_love = request.POST.get('islove')
        print("aaaaaaaaaaaaaaaa")
        print(music_id,is_love,type(is_love))
        print("aaaaaaaaaaaaaaaa")
        if  is_love=='true':
            Love.objects.filter(
                user_id=request.user.id,
                music_id=music_id
            ).delete()
            print('------------------------------------------------------------')
            return JsonResponse({"islove":False })


        else:
            Love.objects.get_or_create(
                user_id=request.user.id,  # 当前登录用户
                music_id=music_id  # 字符串直接传，Django 自动转整数
            )
            print(request.user.id)
            print(music_id)
            print('--aaaaaaa---------------------------------------------------')
            return JsonResponse({"islove": True})

    else:

        return JsonResponse({"islove":False})




def music_details(request,id):
      # 取 URL 参数 ?id=123
    song = Music.objects.filter(pk=id).first()
    print("11111111111")
    print(id)
    if song and song.cover:

        return render(request,'main/music_details.html',{"id":id ,'title': song.Title,'author': song.author,'audio1': song.audio.url,"cover":song.cover.url})






